import 'dart:convert';

import 'package:get/get.dart';
import '../../../data/services/channel_service.dart';

class DeviceController extends GetxController {
  // 服务实例
  final ChannelService _channelService = Get.find<ChannelService>();

  // 响应式变量 - 直接使用，不需要getter
  final isLoading = false.obs;
  final selectedDomainIndex = 0.obs;
  final selectedStatusIndex = 0.obs;

  // 统计数据
  final totalChannels = 0.obs;
  final onlineChannels = 0.obs;
  final offlineChannels = 0.obs;

  // 列表数据
  final channelList = <Map<String, dynamic>>[].obs;
  final organizeList = <Map<String, dynamic>>[].obs;
  final domainList = <Map<String, dynamic>>[].obs;

  // 分页相关
  final currentPage = 1.obs;
  final pageSize = 10.obs;
  final hasMoreData = true.obs;
  final totalCount = 0.obs;

  // 筛选相关
  final statusOptions = ['全部状态', '在线', '离线'].obs;

  // 根据状态筛选的通道列表
  List<Map<String, dynamic>> get filteredChannelList {
    if (selectedStatusIndex.value == 0) {
      return channelList; // 全部状态
    }
    if (selectedStatusIndex.value == 1) {
      return channelList
          .where((channel) => channel['status'] == 'ON')
          .toList(); // 在线
    }
    return channelList
        .where((channel) => channel['status'] == 'OFF')
        .toList(); // 离线
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  /// 初始化数据
  Future<void> _initData() async {
    await Future.wait([
      _loadChannelStatistics(),
      _loadDomainList(),
      _loadOrganizeList(),
    ]);
    await _loadChannelList();
  }

  /// 获取通道数统计
  Future<void> _loadChannelStatistics() async {
    try {
      final response = await _channelService.getChannelStatistics();
      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        onlineChannels.value = data['onlineChannels'] as int? ?? 0;
        offlineChannels.value = data['offlineChannels'] as int? ?? 0;
        totalChannels.value = onlineChannels.value + offlineChannels.value;
        print(
          '获取通道数统计成功：总数${totalChannels.value}，在线${onlineChannels.value}，离线${offlineChannels.value}',
        );
      }
    } catch (e) {
      print('获取通道数统计失败: $e');
    }
  }

  /// 获取域列表
  Future<void> _loadDomainList() async {
    try {
      final response = await _channelService.getDomainList();
      final data = response['data'] as List<dynamic>?;

      // final str = jsonEncode(data);
      if (data != null) {
        domainList.value = data.cast<Map<String, dynamic>>();
        print('获取域列表成功：${domainList.length}个域');
      }
    } catch (e) {
      print('获取域列表失败: $e');
    }
  }

  /// 获取通道列表
  Future<void> _loadChannelList({bool isRefresh = false}) async {
    if (isLoading.value) return;

    try {
      isLoading.value = true;

      if (isRefresh) {
        currentPage.value = 1;
        hasMoreData.value = true;
      }

      // 根据状态筛选参数
      String? statusParam;
      if (selectedStatusIndex.value == 1) {
        statusParam = 'ON'; // 在线
      } else if (selectedStatusIndex.value == 2) {
        statusParam = 'OFF'; // 离线
      }

      // 根据域筛选参数
      String? domainIdParam;
      if (selectedDomainIndex.value > 0 && domainList.isNotEmpty) {
        final selectedDomain = domainList[selectedDomainIndex.value - 1];
        domainIdParam = selectedDomain['id']?.toString();
      }

      final response = await _channelService.getChannelList(
        domainId: domainIdParam,
        status: statusParam,
        pageNo: currentPage.value,
        pageSize: pageSize.value,
      );

      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        final records = data['records'] as List<dynamic>? ?? [];
        final total = data['total'] as int? ?? 0;
        final pages = data['pages'] as int? ?? 0;

        totalCount.value = total;

        if (isRefresh) {
          channelList.value = records.cast<Map<String, dynamic>>();
        } else {
          channelList.addAll(records.cast<Map<String, dynamic>>());
        }

        hasMoreData.value = currentPage.value < pages;

        print('获取通道列表成功：当前页${currentPage.value}，总数$total');
      }
    } catch (e) {
      print('获取通道列表失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 获取组织列表
  Future<void> _loadOrganizeList() async {
    try {
      final response = await _channelService.getOrganizeList();
      final data = response['data'] as List<dynamic>?;
      if (data != null) {
        organizeList.value = data.cast<Map<String, dynamic>>();
        print('获取组织列表成功：${organizeList.length}个组织');
      }
    } catch (e) {
      print('获取组织列表失败: $e');
    }
  }

  /// 切换域选择
  void changeDomain(int index) {
    selectedDomainIndex.value = index;
    _refreshChannelList();
  }

  /// 切换状态筛选
  void changeStatus(int index) {
    selectedStatusIndex.value = index;
    _refreshChannelList();
  }

  /// 刷新通道列表
  Future<void> _refreshChannelList() async {
    await _loadChannelList(isRefresh: true);
    await _loadChannelStatistics();
  }

  /// 加载更多通道
  Future<void> loadMoreChannels() async {
    if (!hasMoreData.value || isLoading.value) return;

    currentPage.value++;
    await _loadChannelList();
  }

  /// 手动刷新
  Future<void> refreshData() async {
    await Future.wait([
      _loadChannelStatistics(),
      _loadDomainList(),
      _loadOrganizeList(),
    ]);
    await _loadChannelList(isRefresh: true);
  }

  /// 获取通道详情
  Future<Map<String, dynamic>?> getChannelDetail(String hsId) async {
    try {
      final response = await _channelService.getChannelDetail(hsId);
      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        print('获取通道详情成功: ${data['channelName']}');
        return data;
      }
    } catch (e) {
      print('获取通道详情失败: $e');
    }
    return null;
  }
}
